package com.xiaodao.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by xiaodao
 * date: 2019/12/7
 * 服务端监听5个端口
 */
public class NioTestSelector12 {


    public static void main(String[] args) throws Exception {
        int[] ports =  new int[5];
        ports[0] =5000;
        ports[1] =5001;
        ports[2] =5002;
        ports[3] =5003;
        ports[4] =5004;

        Selector selector =  Selector.open();

        for (int i = 0; i < ports.length; i++) {
            ServerSocketChannel socketChannel = ServerSocketChannel.open();
            socketChannel.configureBlocking(false);
            ServerSocket socket = socketChannel.socket();
            InetSocketAddress inetSocketAddress = new InetSocketAddress(ports[i]);
            socket.bind(inetSocketAddress);
            socketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("监听端口:" + ports[i]);
        }

        while (true){
            int select = selector.select();
            System.out.println("selectnumber: "+ select);
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            System.out.println("selectionKeys " + selectionKeys.size());
            //这里有可能是多个通道.
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if(selectionKey.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    iterator.remove();
                    System.out.println("获取客户端的连接"+ socketChannel.getRemoteAddress());

                }else if (selectionKey.isReadable()){
                int bytesRead = 0;
                    while (true){
                        System.out.println("读取1次");
                        ByteBuffer byteBuffer =  ByteBuffer.allocateDirect(10);
                        byteBuffer.clear();
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        socketChannel.configureBlocking(false);
                        int read = socketChannel.read(byteBuffer);
                        if(read <=0 ){
                            break;
                        }
                        bytesRead+=read;
                        byteBuffer.flip();
                        socketChannel.write(byteBuffer);
                    }

                    System.out.println("读取的字节: "+ bytesRead);
                    iterator.remove();
                }
            }
        }
    }
}
